﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace Homework7
{
    public partial class Form1 : Form
    {
        private Graphics graphics;
        double th1 = 30 * Math.PI / 180;
        double th2 = 20 * Math.PI / 180;
        double per1 = 0.6;
        double per2 = 0.7;
        double leng = 100;
        int n = 10;
        Color color = Color.Blue;
        

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtN.Text != "")
                n = Int32.Parse(txtN.Text);
            if (txtLeng.Text != "")
                leng = Double.Parse(txtLeng.Text);
            if (txtTh1.Text != "")
            {
                th1 = double.Parse(txtTh1.Text) * Math.PI / 180;
            }
            if (txtTh2.Text != "")
            {
                th2 = double.Parse(txtTh1.Text) * Math.PI / 180;
            }
            per1 = Double.Parse(
                numericUpDownPer1.Value.ToString());
            per2 = Double.Parse(
                numericUpDown2.Value.ToString());

            
            if(graphics == null)
            graphics = panel1.CreateGraphics();
            else
            {
                graphics.Clear(panel1.BackColor);
                graphics.Dispose();
                graphics = panel1.CreateGraphics();
            }
            
            
            drawCayleyTree(n, 200, 310, leng, -Math.PI / 2);
        }

        void drawCayleyTree(int n,double x0,double y0,double leng,double th)
        {
            if (n == 0) return;
            double x1 = x0 + leng * Math.Cos(th);
            double y1 = y0 + leng * Math.Sin(th);
            
            graphics.DrawLine(
                new Pen(color,1), (int)x0, (int)y0, (int)x1, (int)y1);
            drawCayleyTree(n - 1, x1, y1, per1 * leng,th + th1);
            drawCayleyTree(n - 1, x1, y1, per2 * leng, th - th2);


        }

        private void button2_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            color = colorDialog1.Color;
            button2.BackColor = color;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            panel1.BackColor = Color.White;
        }
    }
}
